﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using HttpServer;
using System.Net;
using System.IO;
using HttpListener=HttpServer.HttpListener;
namespace WFWS.WorkerProcess
{
    public partial class Service1 : ServiceBase
    {
        HttpListener listener;
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            listener = HttpListener.Create(IPAddress.Any, 8081);
            listener.RequestReceived += OnRequest;
            listener.Start(50);
        }

        private void OnRequest(object source, RequestEventArgs args)
        {
            IHttpClientContext context = (IHttpClientContext)source;
            IHttpRequest request = args.Request;

            // Respond is a small convenience function that let's you send one string to the browser.
            // you can also use the Send, SendHeader and SendBody methods to have total control.
            if (request.Uri.AbsolutePath == "/hello")
                context.Respond("Hello to you too!"); 

            else if (request.UriParts.Length == 1 && request.UriParts[0] == "goodbye")
            {
            	IHttpResponse response = request.CreateResponse(context);
                StreamWriter writer = new StreamWriter(response.Body);
                writer.WriteLine("Goodbye to you too!");
                writer.Flush();
                response.Send();
            }
        }

        public void EndTutorial()
        {
            listener.Stop();
        }

        public string Name
        {
            get { return "Demo of HttpListener";  }
        }

        protected override void OnStop()
        {
            listener.Stop();
        }

        private void process1_Exited(object sender, EventArgs e)
        {

        }
    }
}
